package com.hth.service;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ClientThread extends Thread { // make class public
	
	private Socket socket;
	private ObjectOutputStream output;
	private ObjectInputStream input;
	private Socket connection;

	public ClientThread(Socket socket) throws IOException {
		this.socket = socket;
	}

	public void run() {
		try {
			connection = socket;
			output = new ObjectOutputStream(socket.getOutputStream());
			output.flush();
			input = new ObjectInputStream(socket.getInputStream());
			
			String message = "Connection Sucessful";
			sendData(message);
			do {
				message = (String) input.readObject();
				displayMessage("\n" + message);
			} while (!message.endsWith(">>>END"));
		} catch (Exception classNotFoundException) {
			displayMessage("\nKhong biet kieu doi tuong nhan duoc");
		} finally {
			closeConnection();
		}
	}

	private void closeConnection() {
		displayMessage("\ndong ket noi\n");
		try {
			output.close();
			input.close();
			connection.close();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	private void displayMessage(final String string) {
		System.out.println(string);
	}

	private void sendData(String message) {
		try {
			output.writeObject("SERVER>>> " + message);
			output.flush();
		} catch (IOException ioException) {
			displayMessage("\nLoi ghi Object");
		}
	}
}